<?php
declare(strict_types=1);

namespace App\AdminApi\Module\System\Search;

use App\Common\Model\System\SmsModel;
use App\Common\Query\Query;
use App\Sys;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Zms\Basics\BasicsSearch;
use Zms\Excel\Export;
use Zms\Sms\Sms;
use Zms\Unit\Arr;
use Zms\Unit\Is;

class SmsSearch extends BasicsSearch
{
    public function query(): Builder
    {
        return SmsModel::query()
            ->when(isset($this->where['phone']) && Is::notEmpty($this->where['phone']), function (Builder $query) {
                Query::LikeSearch($query, 'phone', $this->where['phone']);
            })
            ->when(isset($this->where['status']) && Is::notEmpty($this->where['status']), function (Builder $query) {
                $query->where('status', $this->where['status']);
            })
            ->when(isset($this->where['template_id']) && Is::notEmpty($this->where['template_id']), function (Builder $query) {
                $query->where('template_id', $this->where['template_id']);
            })
            ->orderByRaw($this->order);
    }


    public function HanderData(array $data): array
    {
        $drivers = Arr::map(Sms::drives(), 'drive', 'desc');
        foreach ($data as &$item) {
            $item['driver'] = $drivers['Zms\Sms\Drive\\' . $item['driver']] ?? '';
        }
        return parent::HanderData($data); // TODO: Change the autogenerated stub
    }

    /**
     * 导出短信记录
     * @param string $filename
     * @return array
     */
    public function export(string $filename): array
    {
        $ExportData = [];
        $this->query()->chunk(200, function (Collection $users) use (&$ExportData) {
            foreach ($users->toArray() as $item) {
                $ExportData[] = [
                    $item['phone'],
                    $item['status'] ? '成功' : '失败',
                    $item['content'],
                    date("Y-m-d H:i:s", $item['send_at'])
                ];
            }
        });
        $path = (new Export(Sys::getAssetsPath('/export')))
            ->setFileName('短信发送记录')
            ->setColumn(['手机号', '状态', '短信内容', '发送时间'])
            ->setData($ExportData)
            ->save();
        return ['file' => $path, 'url' => Sys::getAssetsUrl($path)];
    }
}